package com.handpay.nocardpay.baselibrary.utils;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.text.TextUtils;

import com.handpay.nocardpay.baselibrary.config.NoCardPayConfig;
import com.handpay.nocardpay.baselibrary.crypto.LocalEncrypt;
import com.handpay.nocardpay.baselibrary.logutils.HPLog;

import java.util.Hashtable;
import java.util.UUID;


public class ClientEngine {
    private Context mContext;
    // 服务端地址
    public String APPSERVERURL = NoCardPayConfig.APPSERVER;
    // 客户端版本号
    public String VERSION = "1.0.0";
    public String CHANNEL = NoCardPayConfig.CHANNEL;
    public String CLIENTCHANNEL = NoCardPayConfig.CLIENTCHANNEL;
    public final String FASTBILLCHANNEL = "FASTBILL";
    public String HPVIRSION = NoCardPayConfig.HPVIRSION;
    public String DEVICE_ID = "";
    public final String MOBILE_TYPE = "ANDROID";


    public String NO_CARD_PAYMENT_URL_TEST = "https://app.handbank.cn/hpayMicroWap/nocardpay/zztNoCardPayTransfer.htm?";
    public String QR_CODE_PAY_URL_TEST = "https://app.handbank.cn/hpayMicroWap/scanpay/index.htm?";
    public String LOTTERY_URL_TEST = "https://app.handbank.cn/hpayMicroWap/prize/showClientPrizeIndex.htm?";


    /**
     * 终端设备唯一标识：0/1 + 32位十六进制字符串；(0：iOS；1：Android)
     * 2017-03-10 修改不写入setting.db
     *
     * @return
     */
    public String getDeviceUuid() {
        String terminalUnique = PreferenceManager.getInstance(mContext).getString("X-HPTUDID", "");
//        terminalUnique = String.valueOf(getRMSData("X-HPTUDID") == null ? "" : getRMSData("X-HPTUDID"));
        if (null == terminalUnique || terminalUnique.length() <= 2 || terminalUnique.equals("null")) {
            UUID uuidstring = UUID.randomUUID();
            String uuid = "1" + uuidstring.toString().replace("-", "");
//            saveRMSData("X-HPTUDID", uuid);
            PreferenceManager.getInstance(mContext).putString("X-HPTUDID", uuid);
            terminalUnique = uuid;
        }
        return terminalUnique;
    }

    private Hashtable<String, Object> hashGlobal = new Hashtable();

    private static ClientEngine ce;

    public static ClientEngine getInstance() {
        if (ce == null) {
            ce = new ClientEngine();
        }
        return ce;
    }

    public void onDestroy() {
        ce = null;
    }


    /**
     * 初始化，必须最先调用
     *
     * @param context      项目的Activity
     * @param hpversion    服务端协议版本号
     * @param appServerUrl 服务端地址
     * @param channel      渠道号
     */
    public void init(Context context, String hpversion, String appServerUrl, String channel) {
        this.mContext = context;
//        this.DEVICE_ID = ((TelephonyManager) this.mContext.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
//        preferenceManager = PreferenceManager.getInstance(context);
        this.DEVICE_ID = getDeviceUuid();
        this.VERSION = getVersion(context);
        HPVIRSION = hpversion;
        APPSERVERURL = appServerUrl;
        CHANNEL = channel;
    }

    /**
     * 获取客户端版本号
     *
     * @return
     */
    public int getVersionCode() {
        PackageManager manager = mContext.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), PackageManager.PERMISSION_GRANTED);
            return info.versionCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return -1;
    }

    /**
     * 保存数据为全局
     *
     * @param key
     * @param data
     * @return
     */
    public void saveGlobal(String key, Object data) {
        if (hashGlobal.containsKey(key)) {
            hashGlobal.remove(key);
        }
        if (data != null) {
            hashGlobal.put(key, data);
        }
    }

    /**
     * 删除全局数据
     *
     * @param key
     * @return
     */
    public void removeGlobal(String key) {
        if (hashGlobal.containsKey(key)) {
            hashGlobal.remove(key);
        }

    }


    public void clearGlobal() {
        hashGlobal.clear();
    }

    /**
     * 读取全局数据
     *
     * @param key
     * @return
     */
    public Object getGlobal(String key) {
        return getGlobal(key, "");
    }

    public Object getGlobal(String key, Object defaultValue) {
        if (hashGlobal.containsKey(key)) {
            return hashGlobal.get(key);
        } else {
            return defaultValue;
        }
    }

    /**
     * 读取本地保存的数据
     *
     * @return
     */
    public synchronized String getRMSData(String key) {
        String tempEncryData = PreferenceManager.getInstance(mContext).getString(key, "");
        if (TextUtils.isEmpty(tempEncryData)) {
            return null;
        }
        return LocalEncrypt.with().decryptMode(tempEncryData);
    }

    /**
     * 移除某个数据
     *
     * @param key
     */
    public synchronized void removedData(String key) {
        PreferenceManager.getInstance(mContext).remove(key);
    }

    /**
     * 保存数据到本地
     *
     * @param key
     * @param data
     * @return
     */
    public synchronized void saveRMSData(String key, String data) {
        if (!TextUtils.isEmpty(data)) {
            String temp = LocalEncrypt.with().encryptMode(data);
            HPLog.i(HPLog.LFP_TAG, "saveRMSData::temp=" + temp);
            PreferenceManager.getInstance(mContext).putString(key, temp);
        }
    }

    /**
     * 判断应用是否存在
     *
     * @param packageName
     * @return
     */
    public boolean checkBrowser(Context context, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 获取版本号
     *
     * @param mContext
     */
    private String getVersion(Context mContext) {
        String version = null;
        PackageManager manager = mContext.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(mContext.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return version;
    }
}